//
//  HJGoogleAuthenticator.m
//  GoogleLoginICloud
//
//  Created by lx on 2024/1/6.
//

#import "HJGoogleAuthenticator.h"

@implementation HJGoogleAuthenticator


+ (BOOL)handleURL:(NSURL *)url {
    return [GIDSignIn.sharedInstance handleURL:url];
}

+ (void)signInWithPresentingViewController:(UIViewController *)presentingViewController completion:(void (^__nullable)(GIDGoogleUser * _Nullable user, NSError *error))completion {
    
    if (GIDSignIn.sharedInstance.currentUser) {
        [GIDSignIn.sharedInstance.currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
            completion(user, error);
            [self logInfo:user error:error];
        }];
    } else {
        GIDConfiguration *fonfiguration = [[GIDConfiguration alloc] initWithClientID:getGoogleGIDClientID()];
        GIDSignIn.sharedInstance.configuration = fonfiguration;
        [GIDSignIn.sharedInstance signInWithPresentingViewController:presentingViewController completion:^(GIDSignInResult *signInResult, NSError *error) {
            
            if (completion) {
                completion(signInResult.user, error);
            }
            
            [self logInfo:signInResult.user error:error];
        }];
    }
}

+ (void)bindingWithPresentingViewController:(UIViewController *)presentingViewController completion:(void (^__nullable)(GIDGoogleUser * _Nullable user, NSError *error))completion {
    
    GIDConfiguration *fonfiguration = [[GIDConfiguration alloc] initWithClientID:getGoogleGIDClientID()];
    GIDSignIn.sharedInstance.configuration = fonfiguration;
    [GIDSignIn.sharedInstance signInWithPresentingViewController:presentingViewController completion:^(GIDSignInResult *signInResult, NSError *error) {
        
        if (completion) {
            completion(signInResult.user, error);
        }
        
        [self logInfo:signInResult.user error:error];
    }];
}

+ (void)logInfo:(GIDGoogleUser *)user error:(NSError *)error {
    
    NSLog(@"error = %@", error);
    NSLog(@"user.grantedScopes = %@", user.grantedScopes);
    NSLog(@"idToken.tokenString = %@", user.idToken.tokenString);
    NSLog(@"idToken.expirationDate = %.f", user.idToken.expirationDate.timeIntervalSince1970);
    
    NSLog(@"tokenString = %@", user.accessToken.tokenString);
    NSLog(@"accessToken.expirationDate = %.f", user.accessToken.expirationDate.timeIntervalSince1970);
    
    NSLog(@"userId = %@", user.userID);
    NSLog(@"email = %@", user.profile.email);
    NSLog(@"name = %@", user.profile.name);
    NSLog(@"givenName = %@", user.profile.givenName);
    NSLog(@"familyName = %@", user.profile.familyName);
    NSLog(@"hasImage = %d", user.profile.hasImage);
    NSLog(@"ImageUrl = %@", [user.profile imageURLWithDimension:100]);
}


@end
